package com.hgy.chapter2.helper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hgy.chapter2.utils.CollectionUtil;
import com.hgy.chapter2.utils.PropsUtil;

public final class DatabaseHelper {

	private static final Logger LOOGER = LoggerFactory
			.getLogger(PropsUtil.class);

	private static final QueryRunner QUERY_RUNNER = new QueryRunner();

	private static final ThreadLocal<Connection> CONNECTION_HOLDER = new ThreadLocal<Connection>();

	private static final BasicDataSource DATA_SOURCE;

	static {
		Properties conf = PropsUtil.LoadProps("config.properties");

		String driver = conf.getProperty("jdbc.driver");
		String url = conf.getProperty("jdbc.url");
		String username = conf.getProperty("jdbc.username");
		String password = conf.getProperty("jdbc.password");

		DATA_SOURCE = new BasicDataSource();
		DATA_SOURCE.setDriverClassName(driver);
		DATA_SOURCE.setUrl(url);
		DATA_SOURCE.setUsername(username);
		DATA_SOURCE.setPassword(password);

	}

	/**
	 * getConnection
	 * 
	 * @return
	 */
	public static Connection getConnection() {

		// 从本地线程中获取连接
		Connection conn = CONNECTION_HOLDER.get();

		if (conn == null) {
			try {
				// 通过dbcp数据库连接池获取连接
				conn = DATA_SOURCE.getConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				CONNECTION_HOLDER.set(conn);
			}
		}
		return conn;

	}

	/**
	 * queryEntityList
	 * 
	 * @param conn
	 * @param entityClass
	 * @param sql
	 * @param params
	 * @return
	 */
	public static <T> List<T> queryEntityList(Class<T> entityClass, String sql,
			Object... params) {

		List<T> entityList;
		try {
			Connection conn = getConnection();
			entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(
					entityClass), params);
		} catch (Exception e) {
			LOOGER.error("query entity list failure", e);
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return entityList;

	}

	/**
	 * queryEntity
	 * 
	 * @param entityClass
	 * @param sql
	 * @param params
	 * @return
	 */
	public static <T> T queryEntity(Class<T> entityClass, String sql,
			Object... params) {

		T entity;
		try {
			Connection conn = getConnection();
			entity = QUERY_RUNNER.query(conn, sql, new BeanHandler<T>(
					entityClass), params);
		} catch (Exception e) {
			LOOGER.error("query entity failure", e);
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return entity;

	}

	/**
	 * 
	 * 
	 * @param entityClass
	 * @param sql
	 * @param params
	 * @return
	 */
	public static <T> List<Map<String, Object>> executeQuery(
			Class<T> entityClass, String sql, Object... params) {

		List<Map<String, Object>> result;
		try {
			Connection conn = getConnection();
			result = QUERY_RUNNER
					.query(conn, sql, new MapListHandler(), params);
		} catch (Exception e) {
			LOOGER.error("execute query failure", e);
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return result;

	}

	public static int executeUpdate(String sql, Object... params) {

		int row = 0;
		try {
			Connection conn = getConnection();
			row = QUERY_RUNNER.update(conn, sql, params);
		} catch (Exception e) {
			LOOGER.error("execute update failure", e);
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return row;
	}

	public static <T> boolean insertEntity(Map<String, Object> fieldMap) {

		if (CollectionUtil.isEmpty(fieldMap)) {
			LOOGER.error("can not insert entity: fieldMap is empty");
			return false;
		}

		// INSERT INTO tb_customer (, , , ,) values (?,?,?,?)
		String sql = "INSERT INTO tb_customer ";

		StringBuilder columns = new StringBuilder("(");
		StringBuilder values = new StringBuilder("(");
		for (String fieldName : fieldMap.keySet()) {
			columns.append(fieldName).append(", ");
			values.append("?, ");

		}

		columns.replace(columns.lastIndexOf(","), columns.length(), ")");
		values.replace(values.lastIndexOf(","), values.length(), ")");

		sql += columns + "VALUES " + values;

		System.out.println(sql);

		Object[] params = fieldMap.values().toArray();

		return executeUpdate(sql, params) == 1;

	}

	public static <T> boolean updateEntity(Long id, Map<String, Object> fieldMap) {

		if (CollectionUtil.isEmpty(fieldMap)) {
			LOOGER.error("can not update entity: fieldMap is empty");
			return false;
		}

		// UPDATE tb_customer SET xxx = ? WHERE id = ?
		String sql = "UPDATE tb_customer SET ";

		StringBuilder columns = new StringBuilder();
		for (String fieldName : fieldMap.keySet()) {
			columns.append(fieldName).append("=?, ");

		}

		sql += columns.substring(0, columns.lastIndexOf(", ")) + " WHERE id=?";

		System.out.println(sql);

		List<Object> paramList = new ArrayList<Object>();
		paramList.addAll(fieldMap.values());
		paramList.add(id);

		Object[] params = paramList.toArray();

		return executeUpdate(sql, params) == 1;

	}

	public static <T> boolean deleteEntity(Long id) {

		String sql = "DELETE FROM tb_customer WHERE id = ?";
		return executeUpdate(sql, id) == 1;

	}
	
	public static void executeSqlFile(String filePath){
		 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
		 BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		 try{
			 String sql;
			 while((sql = reader.readLine()) != null){
				 executeUpdate(sql);
			 }
		 }catch(Exception e){
			 LOOGER.error("execute sql file failure", e);
			 throw new RuntimeException(e);
		 }
	}
}
